#include "usr_bk.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


status usr_bk_init(usr_bk_list *l){
	l->next=NULL;
	l->bks=NULL;
	return ok;
}


status jie(usr_bk_list *l,unsigned int *uid,char *bid){
	usr_bk_list *p;
	p=l->next;
	//insert into the exist uid
	while(p){
		if(cmp_uid(uid,p->uid)==0){
			bk_list *bknode=(bk_list*)malloc(sizeof(bk_list));
			if(!bknode)exit(overflow);
			strcpy(bknode->bid,bid);
			bknode->next=NULL;
			bk_list *q=p->bks;
			if(!q){
				p->bks=bknode;
				return ok;
			}
			while(q && q->next)q=q->next;
			q->next=bknode;
			return ok;
		}
		p=p->next;
	}
	//create new uid and insert bid
	//0.find the tail of the usr_bk_list
	p=l;
	while(p && p->next)p=p->next;
	//create usr_bk_node and init it
	usr_bk_list *ubnode=(usr_bk_list*)malloc(sizeof(usr_bk_list));
	if(!ubnode)exit(overflow);
	ubnode->next=NULL;
	ubnode->bks=NULL;
	for(int i=0;i<10;i++)ubnode->uid[i]=*(uid+i);
	//create the booklist of the usr
	bk_list *bknode=(bk_list*)malloc(sizeof(bk_list));
	if(!bknode)exit(overflow);
	strcpy(bknode->bid,bid);
	bknode->next=NULL;
	//insert the booklist to the usr_bk_list
	ubnode->bks=bknode;
	//insert the ubnode to the list
	p->next=ubnode;
	return ok;
}

status huan(usr_bk_list *l,unsigned int *uid,char *bid){
	usr_bk_list *p;
	p=l->next;
	while(p){
		if(cmp_uid(p->uid,uid)==0){
			bk_list *q=p->bks;
			if(q && strcmp(q->bid,bid)==0){
				p->bks=q->next;
				free(q);
			}else{
				while(q && q->next){
					if(strcmp(q->next->bid,bid)==0){
						bk_list *r=q->next;
						q->next=q->next->next;
						free(r);
						return ok;
					}
					q=q->next;
				}
			}
		}
		p=p->next;
	}
	return error;
}	

extern void print_book_bid(char *bid);
extern void print_usr_uid(unsigned int *uid);

void find_by_uid(usr_bk_list *l,unsigned int *uid){
	print_usr_uid(uid);
	usr_bk_list *p;
	p=l->next;
	while(p){
		if(cmp_uid(p->uid,uid)==0){
			bk_list* q=p->bks;
			while(q){
				print_book_bid(q->bid);
				q=q->next;
			}
			return;
		}
		p=p->next;
	}
}
